<template>
  <div id="index" ref="appRef">
    <div class="bg">
      <dv-loading v-show="loading">Loading...</dv-loading>
      <div class="host-body">
        <div>
          <!-- 顶部title部分 -->
          <el-row>
            <el-col :span="6"><dv-decoration-8 class="title_right" :color="['#008CFF', '#00ADDD']" /></el-col>
            <el-col :span="12">
              <div class="title_text">轴 密 封 装 配 单 元 系 统 大 屏</div>
              <dv-decoration-5 class="title_center" :color="['#008CFF', '#00ADDD']" />
            </el-col>
            <el-col :span="6">
              <div class="title_time">{{ dateYear + dateWeek + dateDay }}</div>
              <dv-decoration-8 :reverse="true" class="title_left" :color="['#008CFF', '#00ADDD']" />
            </el-col>
          </el-row>
          <!-- 主体部分 -->
          <el-row>
            <!-- 第一列 -->
            <el-col :span="7">
              <!-- 饼图部分 -->
              <div class="left_box1">
                <dv-border-box-12 style="padding-top: 10px">
                  <dv-decoration-7 style="width: 100%; height: 30px">告 警 统 计</dv-decoration-7>
                  <div id="Rose_diagram"></div>
                  <!-- <dv-active-ring-chart :config="config" class="left_box1_rose_right" /> -->
                  <!-- <div class="rose_text" v-for="(item, index) in numberData" :key="index">
                    <p>
                      <span class="coin">￥</span>
                      <span class="rose_text_nmb">{{
                        item.number.number
                        }}</span>
                    </p>
                    <p>
                      <span>{{ item.text }}</span>
                      <span class="colorYellow">(件)</span>
                    </p>
                  </div> -->
                </dv-border-box-12>
              </div>
              <!-- 柱状图部分 -->
              <div class="left_box2">
                <dv-border-box-12 style="padding-top: 10px">
                  <dv-decoration-7 style="width: 100%; height: 30px">扭 矩 统 计</dv-decoration-7>
                  <div id="columnar"></div>
                </dv-border-box-12>
              </div>
              <!-- 轮播表格部分 -->
              <!-- <div class="left_box3">
                <dv-border-box-12 style="padding-top: 10px">
                  <dv-scroll-board :config="board_info" class="carousel_list" oddRowBGC="#fff" />
                </dv-border-box-12>
              </div> -->
            </el-col>
            <!-- 第二列 -->
            <el-col :span="10">
              <!-- 中国地图 -->
              <div id="china-map">
                <div class="text">
                  <el-row :gutter="10">
                    <el-col :span="12">
                      <!-- <el-image :src="require('../../assets/visualScreen/fwszs.png')"></el-image> -->
                      <div class="text_content" style="text-align: center;margin-bottom: 40px;">
                        <div class="title" style="color: white;margin-bottom: 20px;">生产计划</div>
                        <div class="count" style="color: #ffc107;font-size: xxx-large;font-weight: 600;">{{prodPlan}}
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <!-- <el-image :src="require('../../assets/visualScreen/fwszs.png')"></el-image> -->
                      <div class="text_content" style="text-align: center;margin-bottom: 40px;">
                        <div class="title" style="color: white;margin-bottom: 20px;">实际生产</div>
                        <div class="count" style="color: #ffc107;font-size: xxx-large;font-weight: 600;">{{prodActual}}
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                  <el-row :gutter="10">
                    <el-col :span="12">
                      <!-- <el-image :src="require('../../assets/visualScreen/fwszs.png')"></el-image> -->
                      <div class="text_content" style="text-align: center;margin-bottom: 20px;">
                        <div class="title" style="color: white;margin-bottom: 20px;">合格率</div>
                        <div class="count" style="color: #ffc107;font-size: xxx-large;font-weight: 600;">{{okPercent}}%
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <!-- <el-image :src="require('../../assets/visualScreen/fwszs.png')"></el-image> -->
                      <div class="text_content" style="text-align: center;margin-bottom: 20px;">
                        <div class="title" style="color: white;margin-bottom: 20px;">不良品</div>
                        <div class="count" style="color: #ffc107;font-size: xxx-large;font-weight: 600;">{{ngQty}}</div>
                      </div>
                    </el-col>
                  </el-row>
                </div>
                <div class="warning">
                  <el-table :max-height="300" :data="tableData" ref="scroll_Table" style="width: 95%;height:300px;margin:0 auto; padding: 17px 0;
                        --el-table-border-color: none;
                        --el-table-bg-color: none;
                        --el-table-tr-bg-color: none;
                        background-color: transparent;" :row-class-name='tableRowClassName'
                    :cell-style="{'color':'#FFFFFF','text-align':'center'}"
                    :header-cell-style="{'background':'#375A88','color':'rgba(2,217,253,0.8)','text-align':'center'}"
                    @mouseenter.native="autoScroll(true)" @mouseleave.native="autoScroll(false)">
                    <el-table-column prop="equipmentCode" label="设备编号" :show-overflow-tooltip="true" />
                    <el-table-column prop="alarmCode" label="告警代码" :show-overflow-tooltip="true" />
                    <el-table-column prop="alarmType" label="告警类型">
                      <template slot-scope="scope">
                        <dict-tag :options="dict.type.alarm_type" :value="scope.row.alarmType" />
                      </template>
                    </el-table-column>
                    <el-table-column prop="alarmContent" label="告警内容" :show-overflow-tooltip="true" />
                    <el-table-column label="告警开始时间" :show-overflow-tooltip="true">
                      <template slot-scope="scope">
                        {{scope.row.alarmStartTime}}
                      </template>
                    </el-table-column>
                    <el-table-column label="告警结束时间" :show-overflow-tooltip="true">
                      <template slot-scope="scope">
                        {{scope.row.alarmEndTime}}
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
              <!-- 折线图 -->
              <div class="line_center">
                <dv-border-box-13>
                  <dv-decoration-7 style="width: 100%; height: 30px;padding-top:30px;">生 产 统 计</dv-decoration-7>
                  <div id="line_center_diagram"></div>
                </dv-border-box-13>
              </div>
            </el-col>
            <!-- 第三列 -->
            <el-col :span="7">
              <!-- 设备连接状态 -->
              <div class="right_box3">
                <dv-border-box-12 :reverse="true">
                  <dv-decoration-7 style="width: 100%; height: 30px">设 备 实 时 状 态</dv-decoration-7>
                  <div class="text">
                    <div class="text_content" style="text-align: center;display: flex;">
                      <div class="title" style="color: white;font-size: x-large;font-weight: 300;">
                        设备编码</div>
                      <div class="count" style="color: #ffc107;font-size: xx-large;font-weight: 600;margin-left: 50px;">{{deviceCode}}
                      </div>
                    </div>
                    <div class="text_content" style="text-align: center;display: flex;">
                      <div class="title" style="color: white;font-size: x-large;">设备状态</div>
                      <div class="count" style="color: #ffc107;font-size: xx-large;font-weight: 600;margin-left: 50px;">{{deviceStatus}}
                      </div>
                    </div>
                  </div>
                </dv-border-box-12>
              </div>
              <!-- 轮播排行榜部分 -->
              <div class="right_box1">
                <dv-border-box-12>
                  <dv-decoration-7 style="width: 100%; height: 30px">生 产 统 计</dv-decoration-7>
                  <dv-scroll-ranking-board :config="config" style="width: 95%; height: 100%; margin-left: 2%" />
                </dv-border-box-12>
              </div>
              <!-- 虚线柱状图部分 -->
              <div class="right_box2">
                <dv-border-box-12 :reverse="true">
                  <dv-decoration-7 style="width: 100%; height: 30px;padding-top:20px;">压 力 统 计</dv-decoration-7>
                  <div id="dotter_bar"></div>
                </dv-border-box-12>
              </div>
              <!-- 部分 -->
              <!-- <div class="right_box3">
                <dv-border-box-12 :reverse="true">
                  <dv-conical-column-chart :config="cone" class="cone_box" />
                </dv-border-box-12>
              </div> -->
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import drawMixin from "./mixins/drawMixin.js"; //自适应缩放
  import { formatDateFMt, formatDate } from "../../utils/index.js"; //日期格式转换
  import { formatMalfunctionData } from "../../utils/formatDicData.js"; //日期格式转换
  import * as echarts from 'echarts'
  import { WarningQuery, getYeild, CollectDataQuery,CollectDataQueryNew, LatestProductQuery, ProductRankQuery, MalfunctionStaticsQuery } from '@/api/system/datamanage'
  import moment from 'moment'


  export default {
    mixins: [drawMixin],
    dicts: ['alarm_type'],
    data() {
      return {
        scrolltimer: '', // 自动滚动定时任务
        legendList: [],
        seriesList: [],
        cumulativeData: [],

        // 顶部统计
        okPercent: 0,
        ngQty: 0,
        prodPlan: 0,
        prodActual: 0,
        prodTimes: [],
        // 扭矩统计
        njTimes: [],
        njValues: [],
        intervalId: null, // 定时器ID
        isInitialized: false, // 是否已经找到匹配数据
        njForm: {
          startTime: '',
          dateEnd: '',
          sectionNo: '',
          pageSize: 1,
          pageNum: 1
        },

        // 压力统计
        ylTimes: [], // 保存时间
        ylValuesOne: [], // 保存对应时间的数据
        ylValuesTwo: [],

        prodChart: {},
        njChart: {},
        ylChart: {},
        mapChart: {},

        //定时器
        timing: null,
        //loading图
        loading: true,
        //时分秒
        dateDay: null,
        //年月日
        dateYear: null,
        //周几
        dateWeek: null,
        //周几
        weekday: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
        tableData: [],
        warnQueryParams: {
          pageNum: 1,
          pageSize: 10,
          malfunctionCode: ''
        },
        prodQueryParams: {
          pageNum: 0,
          pageSize: 10
        },
        prodDateRange: [],
        warnDateRange: [],
        //轮播排行榜
        rankingParams: {
          pageNum: 1,
          pageSize: 10,
          roleName: undefined,
          roleKey: undefined,
          status: undefined
        },
        config: {
          data: [
            // {
            //   name: "2024-09-26",
            //   value: 55,
            // },
            // {
            //   name: "2024-09-25",
            //   value: 11,
            // },
            // {
            //   name: "2024-09-24",
            //   value: 78,
            // }, {
            //   name: "2024-09-23",
            //   value: 66,
            // },
            // {
            //   name: "2024-09-23",
            //   value: 80,
            // },
            // {
            //   name: "2024-09-22",
            //   value: 45,
            // },
            // {
            //   name: "2024-09-21",
            //   value: 29,
            // }, {
            //   name: "2024-09-20",
            //   value: 66,
            // }
          ],
        },
        //左侧饼图文字
        numberData: [
          {
            number: {
              number: 15,
            },
            text: "今日构建总量",
          },
          {
            number: {
              number: 1144,
            },
            text: "总共完成数量",
          },
          {
            number: {
              number: 361,
            },
            text: "正在编译数量",
          },
        ],
        //左侧轮播表格配置项
        board_info: {
          header: ["人员", "月产量", "月合格率"],
          data: [
            ["张三", "10830", "90%"],
            ["张四", "13500", "92%"],
            ["张五", "10350", "97%"],
            ["张六", "13300", "94%"],
            ["张七", "12500", "95%"],
            ["张八", "11500", "96%"],
            ["张九", "12500", "89%"],
            ["王六", "10360", "95%"],
            ["王二", "10567", "91%"],
            ["李四", "15721", "99%"],
          ],
          evenRowBGC: "#020308",
          oddRowBGC: "#382B47",
          headerBGC: "#020308",
        },
        // 定义颜色
        colorList: {
          linearYtoG: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "#f5b44d",
              },
              {
                offset: 1,
                color: "#28f8de",
              },
            ],
          },
          linearGtoB: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: "#43dfa2",
              },
              {
                offset: 1,
                color: "#28f8de",
              },
            ],
          },
          linearBtoG: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 1,
            y2: 0,
            colorStops: [
              {
                offset: 0,
                color: "#1c98e8",
              },
              {
                offset: 1,
                color: "#28f8de",
              },
            ],
          },
          areaBtoG: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(35,184,210,.2)",
              },
              {
                offset: 1,
                color: "rgba(35,184,210,0)",
              },
            ],
          },
        },
      };
    },
    mounted() {
      this.isInitialized = false
      // 获取生产数据
      this.getProductList()
      //获取实时时间
      this.timeFn();
      //加载loading图
      this.cancelLoading();
      // 获取告警列表
      this.getWarningList()
      //左侧玫瑰饼图
      this.Rose_diagram();
      this.initRoseDiagram()
      //左侧柱状图
      this.columnar();
      this.updateNjData();
      //中间折线图
      this.line_center_diagram();
      this.updateData();
      setInterval(this.updateData, 60 * 60 * 1000); // 每1小时更新一次
      // 设置定时任务，每天凌晨重置
      this.scheduleResetAtMidnight();
      //虚线柱状图
      this.dotter_bar();
      //生产排行榜
      this.reflashProdRanking();
      this.fetchProductionCounts();
      this.autoScroll()
    },
    beforeDestroy() {
      //离开时删除计时器
      clearInterval(this.timing);
      clearInterval(this.intervalId)
      this.timing = null
      this.intervalId = null
      this.isInitialized = true
      this.autoScroll(true)
    },
    created() {
      // 组件创建时初始化日期和数据
      this.initializeTimes();
      this.initializeNjTimes();
      this.getWarningList()
      // 每天更新数据
    },
    deactivated() {
      clearInterval(this.timing);
      clearInterval(this.intervalId)
      this.timing = null
      this.intervalId = null
      this.isInitialized = true
    },
    methods: {
      reflashProdRanking() {
        this.fetchProductionCounts();

      },
      // 获取生产数量
      async fetchProductionCounts() {
        const dateRanges = [];
        this.config.data = [];
        let newarr = []
        const res = await ProductRankQuery(this.rankingParams);
        if (res.data != null || res.data.length > 0) {
          res.data.forEach(element => {
            newarr.push({ name: element.time, value: element.value })
          })
          this.config.data = newarr
          this.config = { ...this.config }
        }
      },
      getWarningList() {
        // this.loading = true;
        let startTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + '00:00:00';
        let endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + '23:59:59';
        // this.tableData = JSON.parse('[{"ID":0,"deviceCode":"11","malfunctionName":"11","malfunctionCode":"11","malfunctionNote":null,"startTIme":"2024-09-14T13:45:08","endTime":"2024-09-14T13:45:08","remark":null,"createTime":"2024-09-14T13:45:08","updateTime":"2024-09-20T18:13:58.2251644+08:00"},{"ID":0,"deviceCode":"XD001","malfunctionName":null,"malfunctionCode":"02-8501","malfunctionNote":null,"startTIme":"2024-09-20T18:13:58.2251644+08:00","endTime":"2024-09-20T18:13:58.2251644+08:00","remark":null,"createTime":"2024-09-20T00:00:03","updateTime":"2024-09-20T18:13:58.2251644+08:00"},{"ID":0,"deviceCode":"XD001","malfunctionName":null,"malfunctionCode":"02-8501","malfunctionNote":null,"startTIme":"2024-09-20T18:13:58.2251644+08:00","endTime":"2024-09-20T18:13:58.2251644+08:00","remark":null,"createTime":"2024-09-20T00:00:03","updateTime":"2024-09-20T18:13:58.2251644+08:00"},{"ID":0,"deviceCode":"XD001","malfunctionName":null,"malfunctionCode":"02-8501","malfunctionNote":null,"startTIme":"2024-09-20T18:13:58.2251644+08:00","endTime":"2024-09-20T18:13:58.2251644+08:00","remark":null,"createTime":"2024-09-20T00:00:03","updateTime":"2024-09-20T18:13:58.2251644+08:00"}]')
        WarningQuery(this.warnQueryParams).then(response => {
          let list = response.rows
          this.tableData = list;
          // this.total = this.alarmList.length;
          // this.loading = false;
        });
      },
      /** 查询生产列表 */
      getProductList() {
        // this.loading = true;
        let startTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + '00:00:00';
        let endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + '23:59:59';
        // 获取最新的生产数据
        LatestProductQuery(this.addDateTimeRange(this.prodQueryParams, [startTime, endTime])).then(response => {
          if (response.data != null) {
            const latestProd = response.data;
            this.prodPlan = parseFloat(latestProd.productionPlanning);
            this.ngQty = parseFloat(latestProd.defectiveProducts);
            this.prodActual = parseFloat(latestProd.actualProduction);
            this.okPercent = parseFloat(latestProd.rateOfCompletion);
          }
        })
      },
      tableRowClassName(rowIndex) {
        if (rowIndex.rowIndex % 2 != 0) {
          console.log('rowIndex', rowIndex.rowIndex)
          return 'evenRow';
        }
        return 'oddRow';
      },
      //右上角当前日期时间显示：每一秒更新一次最新时间
      timeFn() {
        this.timing = setInterval(() => {
          //获取当前时分秒
          this.dateDay = formatDateFMt(new Date(), "HH: mm: ss");
          //获取当前年月日
          this.dateYear = formatDateFMt(new Date(), "yyyy-MM-dd");
          //获取当前周几
          this.dateWeek = this.weekday[new Date().getDay()];
        }, 1000);
      },
      //loading图
      cancelLoading() {
        setTimeout(() => {
          this.loading = false;
        }, 500);
      },
      initRoseDiagram() {
        // this.loading = true;
        let startTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + '00:00:00';
        let endTime = formatDate(new Date());
        console.log("开始时间：" + startTime)
        console.log("结束时间：" + endTime)
        // 获取当月告警数据
        MalfunctionStaticsQuery(this.addDateTimeRange(this.warnQueryParams, [startTime, endTime])).then(response => {
          if (response.data.data != null) {
            this.malfunctionTypeList = response.data.data;
            const malfuntionList = formatMalfunctionData(this.malfunctionTypeList)
            // console.log(malfuntionList)
            // 更新扭矩图表
            this.mapChart.setOption({
              legend: [{ data: malfuntionList }],
              series: [{
                data: malfuntionList
              }]
            });
          }
        })
      },
      //   //玫瑰饼图
      Rose_diagram() {
        this.mapChart = echarts.init(
          document.getElementById("Rose_diagram")
        ); //图表初始化，china-map是绑定的元素
        window.onresize = this.mapChart.resize; //如果容器变大小，自适应从新构图
        let option = {
          tooltip: {
            trigger: "item",
            formatter: "{a} <br/>{b} : {c} ({d}%)",
          },
          toolbox: {
            show: true,
          },
          calculable: true,
          legend: {
            orient: "horizontal",
            icon: "circle",
            bottom: 0,
            x: "center",
            data: [],
            textStyle: {
              color: "#fff",
              fontSize: 15
            },
          },
          series: [
            {
              name: "告警",
              type: "pie",
              radius: [20, 100],
              roseType: "area",
              center: ["50%", "40%"],
              data: [],
            },
          ],
        };
        this.mapChart.setOption(option); //生成图表
      },
      //柱状图
      columnar() {
        this.njChart = echarts.init(document.getElementById("columnar")); //图表初始化，china-map是绑定的元素
        window.onresize = this.njChart.resize; //如果容器变大小，自适应从新构图
        let option = {
          title: {
            text: "",
          },
          tooltip: {
            trigger: "axis",
            backgroundColor: "rgba(255,255,255,0.1)",
            axisPointer: {
              type: "shadow",
              label: {
                show: true,
                backgroundColor: "#7B7DDC",
              },
            },
          },
          grid: {
            x: "8%",
            width: "95%",
            y: "4%",
          },
          xAxis: {
            data: this.njTimes,
            axisLine: {
              lineStyle: {
                color: "#B4B4B4",
              },
            },
            axisTick: {
              show: false,
            },
          },
          yAxis: [
            {
              splitLine: { show: false },
              axisLine: {
                lineStyle: {
                  color: "#B4B4B4",
                },
              },
              axisLabel: {
                formatter: "{value} ",
              },
            },
          ],
          graphic: {
            type: 'text',     // 类型：文本
            left: 'center',
            top: 'middle',
            silent: true,     // 不响应事件
            invisible: this.njValues.length > 0,   // 有数据就隐藏
            style: {
              fill: '#9d9d9d',
              fontWeight: 'bold',
              text: '暂无数据',
              fontFamily: 'Microsoft YaHei',
              fontSize: '25px'
            }
          },
          series: [
            {
              name: "扭矩值",
              type: "line",
              barGap: "-100%",
              barWidth: 10,
              itemStyle: {
                normal: {
                  barBorderRadius: 5,
                  color: '#EEAD0E',
                },
              },
              z: -12,
              data: this.njValues,
            },
          ],
        };
        this.njChart.setOption(option); //生成图表
      },
      async updateNjData() {
        try {
          const currentTime = new Date(); // 当前时间
          this.njForm.startTime = this.parseTime(currentTime.getTime() - 1000); // 当前时间减一秒
          this.njForm.dateEnd = this.parseTime(currentTime.getTime() + 1000); // 当前时间加一秒
          const response = await CollectDataQuery(this.njForm);
          if (response.data != null) {
            const { currentMaximumMoment, maximumWorkingMoment1, maximumWorkingMoment2 } = response.data;
            // 将UTC时间转换为本地时间并格式化
            const formattedTime = this.parseTime(currentTime).slice(11, 19);

            // 如果数组已满，移除最早的一个时间数据
            if (this.njTimes.length >= 5) {
              this.njTimes.shift();
              this.njValues.shift();
              this.ylTimes.shift();
              this.ylValuesOne.shift();
              this.ylValuesTwo.shift();
            }

            // 添加新的时间和数据
            this.njTimes.push(formattedTime);
            this.njValues.push(currentMaximumMoment);
            this.ylTimes.push(formattedTime);
            this.ylValuesOne.push(maximumWorkingMoment1);
            this.ylValuesTwo.push(maximumWorkingMoment2);

            // 更新扭矩图表
            this.njChart.setOption({
              xAxis: {
                data: this.njTimes
              },
              series: [{
                data: this.njValues
              }]
            });

            // 更新压力图表
            this.ylChart.setOption({
              xAxis: {
                data: this.ylTimes
              },
              series: [
                {
                  name: '压力值1',
                  type: 'line',
                  data: this.ylValuesOne
                },
                {
                  name: '压力值2',
                  type: 'line',
                  data: this.ylValuesTwo
                }
              ]
            });
          }

        } catch (error) {
          console.error('Error fetching data:', error);
        }
      },
      async initializeNjTimes() {
        while (!this.isInitialized) {
          try {
            const currentTime = new Date(); // 当前时间
            this.njForm.startTime = this.parseTime(currentTime.getTime() - 1000); // 当前时间减一秒
            this.njForm.dateEnd = this.parseTime(currentTime.getTime() + 1000); // 当前时间加一秒
            const res = await CollectDataQuery(this.njForm);
            if (res.data != null) {
              const response = res.data
              // if (response.length > 0) {
              const { currentMaximumMoment, maximumWorkingMoment1, maximumWorkingMoment2 } = response;

              // 将UTC时间转换为本地时间并格式化
              const formattedTime = this.parseTime(currentTime).slice(11, 19);
              console.log("后端返回时间：" + formattedTime)
              console.log(this.parseTime(currentTime, '{h}:{i}:{s}'))
              console.log(this.njForm.startTime.slice(11, 19))
              console.log(this.njForm.dateEnd.slice(11, 19))

              if (formattedTime == this.parseTime(currentTime, '{h}:{i}:{s}') || formattedTime == this.njForm.startTime.slice(11, 19) || formattedTime == this.njForm.dateEnd.slice(11, 19)) {
                console.log("我进来了")
                // 找到匹配的数据
                this.isInitialized = true;
                this.njTimes.push(formattedTime);
                this.njValues.push(currentMaximumMoment);
                this.ylTimes.push(formattedTime);
                this.ylValuesOne.push(maximumWorkingMoment1);
                this.ylValuesTwo.push(maximumWorkingMoment2);

                // 更新扭矩图表
                this.njChart.setOption({
                  xAxis: {
                    data: this.njTimes
                  },
                  graphic: {
                    invisible: this.njValues.length > 0,   // 有数据就隐藏
                  },
                  series: [{
                    data: this.njValues
                  }]
                });

                // 更新压力图表
                this.ylChart.setOption({
                  xAxis: {
                    data: this.ylTimes
                  },
                  graphic: {
                    invisible: this.ylValuesOne.length > 0 || this.ylValuesTwo.length > 0,   // 有数据就隐藏
                  },
                  series: [
                    {
                      name: '压力值1',
                      type: 'line',
                      data: this.ylValuesOne
                    },
                    {
                      name: '压力值2',
                      type: 'line',
                      data: this.ylValuesTwo
                    }
                  ]
                });

                // 开始定时请求
                this.startNjInterval();
              }
              // }
            }
          } catch (error) {
            console.error('Error fetching data:', error);
          }
          // 等待一段时间后再次尝试
          // await new Promise(resolve => setTimeout(resolve, 1000));
        }
      },
      startNjInterval() {
        this.intervalId = setInterval(this.updateNjData, 3 * 1000); // 每3秒更新一次
      },

      //折线图
      line_center_diagram() {
        this.prodChart = echarts.init(
          document.getElementById("line_center_diagram")
        ); //图表初始化，china-map是绑定的元素
        window.onresize = this.prodChart.resize; //如果容器变大小，自适应从新构图
        let option = {
          xAxis: {
            type: "category",
            data: this.prodTimes,
            position: "bottom",
            axisLine: true,
            axisLabel: {
              color: "rgba(255,255,255,.8)",
              fontSize: 12,
            },
          },
          yAxis: {
            type: "value",
            name: "生产量",
            nameLocation: "end",
            nameGap: 24,
            nameTextStyle: {
              color: "rgba(255,255,255,.5)",
              fontSize: 14,
            },
            splitNumber: 4,
            axisLine: {
              lineStyle: {
                opacity: 0,
              },
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: "#fff",
                opacity: 0.1,
              },
            },
            axisLabel: {
              color: "rgba(255,255,255,.8)",
              fontSize: 12,
            },
          },
          grid: {
            left: 50,
            right: 10,
            bottom: 55,
            top: "15%",
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'cross'
            },
            padding: [5, 10]
          },
          legend: {
            data: this.legendList,
            padding: [15, 0, 0, 0],
            textStyle: {
              fontSize: 14,//字体大小
              color: '#ffffff'//字体颜色
            },
          },
          series: this.seriesList
        };
        this.prodChart.setOption(option); //生成图表
      },
      async updateData() {
        // 获取当前时间
        const currentTime = moment().format('HH:mm');
        // 判断是否在更新范围内
        if (moment(currentTime, 'HH:mm').isBetween(moment('08:00', 'HH:mm'), moment('20:00', 'HH:mm'), null, '[]')) {
          // 如果当前时间不是整点，则不更新
          if (currentTime.split(':')[1] !== '00') return;

          // 移除最早的一个时间数据
          this.prodTimes.shift();

          // 添加当前的时间和数据
          this.prodTimes.push(currentTime);
          // this.values.push(Math.floor(Math.random() * 100)); // 随机生成数据
          let startTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + this.prodTimes[this.prodTimes.length - 2] + ':00';
          let endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + currentTime + ':00';
          let params = {
            pageNum: 1,
            pageSize: 9999
          }
          await getYeild(this.addDateTimeRange(params, [startTime, endTime])).then(response => {
            if (response.data != null && response.data.length > 0) {
              this.qualifiedList = response.data;

              console.log(this.qualifiedList);
              this.qualifiedList.forEach(element => {
                let productName = element.productName
                if (!this.cumulativeData[productName]) {
                  this.cumulativeData[productName] = { acceptance: [], belowStandard: [] };
                }
                // 累积合格和不合格的数量
                this.cumulativeData[productName].acceptance.push(element.acceptanceNumber);
                this.cumulativeData[productName].belowStandard.push(element.belowStandardNumber);
              });
              for (var productName in this.cumulativeData) {
                this.legendList.push(productName + '-合格品');
                this.legendList.push(productName + '-不合格品');

                this.seriesList.push({
                  name: productName + '-合格品',
                  type: 'line',
                  data: this.cumulativeData[productName].acceptance,
                  lineStyle: {
                    color: productName === "5KA.206.140-name" ? 'green' : 'blue'
                  }
                });

                this.seriesList.push({
                  name: productName + '-不合格品',
                  type: 'line',
                  data: this.cumulativeData[productName].belowStandard,
                  lineStyle: {
                    color: productName === "5KA.206.140-name" ? 'red' : 'orange',
                    type: 'dashed'
                  }
                });
              }
            }
          });

        }
        for (var productName in this.cumulativeData) {

          this.legendList.push(productName + '-合格品');
          this.legendList.push(productName + '-不合格品');
          this.seriesList.push({
            name: productName + '-合格品',
            type: 'line',
            data: this.cumulativeData[productName].acceptance,
            lineStyle: {
              color: productName === "5KA.206.140-name" ? 'green' : 'blue'
            }
          });

          this.seriesList.push({
            name: productName + '-不合格品',
            type: 'line',
            data: this.cumulativeData[productName].belowStandard,
            lineStyle: {
              color: productName === "5KA.206.140-name" ? 'red' : 'orange',
              type: 'dashed'
            }
          });
        }
        // 更新图表
        this.prodChart.setOption({
          xAxis: {
            data: this.prodTimes
          },
          legend: {
            data: this.legendList
          },
          series: this.seriesList
        });

      },
      async initializeTimes() {
        // 获取当前时间
        const now = moment();
        // 初始化最近八个小时的时间
        for (let i = 0; i < 8; i++) {
          const time = now.clone().subtract(7 - i, 'hours').startOf('hour').format('HH:mm');
          this.prodTimes.push(time);
          // this.values.push(Math.floor(Math.random() * 100)); // 随机生成初始数据
        }
        for (let i = 1; i < 8; i++) {
          let startTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + this.prodTimes[i - 1] + ':00';
          let endTime = this.parseTime(new Date(), '{y}-{m}-{d}') + ' ' + this.prodTimes[i] + ':00';
          console.log(startTime + "..." + endTime)
          let params = {
            pageNum: 1,
            pageSize: 9999
          }
          await getYeild(this.addDateTimeRange(params, [startTime, endTime])).then(response => {
            if (response.data != null && response.data.length > 0) {
              this.qualifiedList = response.data;

              console.log(this.qualifiedList);
              this.qualifiedList.forEach(element => {
                let productName = element.productName
                if (!this.cumulativeData[productName]) {
                  this.cumulativeData[productName] = { acceptance: [], belowStandard: [] };
                }
                // 累积合格和不合格的数量
                this.cumulativeData[productName].acceptance.push(element.acceptanceNumber);
                this.cumulativeData[productName].belowStandard.push(element.belowStandardNumber);
              });
            }

          });

        }
        for (var productName in this.cumulativeData) {

          this.legendList.push(productName + '-合格品');
          this.legendList.push(productName + '-不合格品');
          this.seriesList.push({
            name: productName + '-合格品',
            type: 'line',
            data: this.cumulativeData[productName].acceptance,
            lineStyle: {
              color: productName === "5KA.206.140-name" ? 'green' : 'blue'
            }
          });

          this.seriesList.push({
            name: productName + '-不合格品',
            type: 'line',
            data: this.cumulativeData[productName].belowStandard,
            lineStyle: {
              color: productName === "5KA.206.140-name" ? 'red' : 'orange',
              type: 'dashed'
            }
          });
        }
        // 更新图表
        this.prodChart.setOption({
          xAxis: {
            data: this.prodTimes
          },
          legend: {
            data: this.legendList
          },
          series: this.seriesList
        });
      },
      scheduleResetAtMidnight() {
        // 计算距离下一个午夜的时间
        const now = moment();
        const nextMidnight = moment().startOf('day').add(1, 'day');
        const delay = nextMidnight.diff(now, 'milliseconds');

        // 在下一个午夜时重置图表
        setTimeout(() => {
          this.resetChart();
          // 每天凌晨重新设置定时任务
          setInterval(this.updateData, 60 * 60 * 1000); // 每1小时更新一次
          this.scheduleResetAtMidnight(); // 递归调用，确保每天凌晨都重置
        }, delay);
      },
      resetChart() {
        // 重置时间和数据
        this.prodTimes = [];
        this.values = [];
        this.initializeTimes();
        // 重新初始化图表
        this.initChart();
      },

      //右侧虚线柱状图图
      dotter_bar() {
        this.ylChart = echarts.init(document.getElementById("dotter_bar")); //图表初始化
        window.onresize = this.ylChart.resize; //如果容器变大小，自适应从新构图
        let option = {
          title: {
            text: "",
          },
          tooltip: {
            trigger: "axis",
            backgroundColor: "rgba(255,255,255,0.1)",
            axisPointer: {
              type: "shadow",
              label: {
                show: true,
                backgroundColor: "#7B7DDC",
              },
            },
          },
          grid: {
            x: "8%",
            width: "95%",
            y: "4%",
          },
          xAxis: {
            data: this.ylTimes,
            axisLine: {
              lineStyle: {
                color: "#B4B4B4",
              },
            },
            axisTick: {
              show: false,
            },
          },
          yAxis: [
            {
              splitLine: { show: false },
              axisLine: {
                lineStyle: {
                  color: "#B4B4B4",
                },
              },
              axisLabel: {
                formatter: "{value} ",
              },
            },
          ],
          graphic: {
            type: 'text',     // 类型：文本
            left: 'center',
            top: 'middle',
            silent: true,     // 不响应事件
            invisible: this.ylValuesOne.length > 0 || this.ylValuesTwo.length > 0,   // 有数据就隐藏
            style: {
              fill: '#9d9d9d',
              fontWeight: 'bold',
              text: '暂无数据',
              fontFamily: 'Microsoft YaHei',
              fontSize: '25px'
            }
          },
          series: [
            {
              name: "压力值1",
              type: "line",
              barGap: "-100%",
              barWidth: 10,
              itemStyle: {
                normal: {
                  barBorderRadius: 5,
                  color: '#EEAD0E',
                },
              },
              z: -12,
              data: this.ylValuesOne,
            },
            {
              name: "压力值2",
              type: "line",
              barGap: "-100%",
              barWidth: 10,
              itemStyle: {
                normal: {
                  barBorderRadius: 5,
                  color: '#7DDA58',
                },
              },
              z: -12,
              data: this.ylValuesTwo,
            },
          ],
        };
        this.ylChart.setOption(option); //生成图表
      },
      // 设置自动滚动
      autoScroll(stop) {
        const table = this.$refs.scroll_Table
        // 拿到表格中承载数据的div元素
        const divData = table.$refs.bodyWrapper

        // 拿到元素后，对元素进行定时增加距离顶部距离，实现滚动效果(此配置为每100毫秒移动1像素)
        if (stop) {
          console.log("停止");

          //再通过事件监听，监听到 组件销毁 后，再执行关闭计时器。
          window.clearInterval(this.scrolltimer)
        } else {
          console.log("开始");

          this.scrolltimer = window.setInterval(() => {
            // 元素自增距离顶部1像素
            divData.scrollTop += 1
            // 判断元素是否滚动到底部(可视高度+距离顶部=整个高度)
            if (divData.clientHeight + divData.scrollTop >= divData.scrollHeight) {
              // 停止当前定时器
              window.clearInterval(this.scrolltimer);
              // 设置短暂延迟后重置scrollTop
              this.scrolltimer = window.setTimeout(() => {
                divData.scrollTop = 0; // 或者使用 divData.scrollTop -= divData.scrollHeight / 2; 以获得不同的效果
                // 重新启动滚动定时器
                this.autoScroll(false);
              }, 500); // 暂停时间，可以调整
            }
          }, 50) // 滚动速度
        }
      },
    },
  };
</script>

<style lang="scss">
  /* 全局样式部分！！！！ */
  * {
    margin: 0;
    padding: 0;
    list-style-type: none;
    outline: none;
    box-sizing: border-box;
  }

  html {
    margin: 0;
    padding: 0;
  }

  body {
    font-family: Arial, Helvetica, sans-serif;
    line-height: 1.2em;
    background-color: #f1f1f1;
    margin: 0;
    padding: 0;
  }

  a {
    color: #343440;
    text-decoration: none;
  }

  /* 页面样式部分！！！！ */
  #index {
    color: #d3d6dd;
    width: 1920px;
    height: 1080px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transform-origin: left top;
    overflow: hidden;

    .bg {
      /* 整体页面背景 */
      width: 100%;
      height: 100%;
      padding: 16px 16px 0 16px;
      /* 背景图 */
      background-image: url("../../assets/visualScreen/bg.png");
      /* 背景尺寸 */
      background-size: cover;
      /* 背景位置 */
      background-position: center center;
    }

    /* 顶部右边装饰效果 */
    .title_left {
      width: 100%;
      height: 50px;
    }

    /* 顶部左边装饰效果 */
    .title_right {
      width: 100%;
      height: 50px;
      margin-top: 18px;
    }

    /* 顶部中间装饰效果 */
    .title_center {
      width: 100%;
      height: 50px;
    }

    /* 顶部中间文字数据可视化系统 */
    .title_text {
      text-align: center;
      font-size: 24px;
      font-weight: bold;
      margin-top: 14px;
      color: #008cff;
    }

    /* 时间日期 */
    .title_time {
      text-align: center;
    }

    /* 中国地图 */
    #china-map {
      height: 502px;
      width: 100%;

      .text {
        width: 23rpx;
        height: 9rpx;
        font-family: LetsgoDigital, LetsgoDigital;
        font-weight: 400;
        font-size: 13rpx;
        color: #1FEEF7;
        line-height: 0rpx;
        text-align: left;
        font-style: normal;
        text-transform: none;
        background: radial-gradient(0deg, #73DAFC 0%, #2DCBFF 100%);
      }

      .text-content {
        text-align: center;

        .count {
          color: #ffc107;
          font-size: x-large;
        }

        .title {
          color: white;
        }
      }

      /* 表格样式 */
      .el-table tr {
        background-color: transparent;
      }

      .el-table tr:hover>td {
        background-color: transparent !important;
      }

      .el-input__wrapper {
        background-color: rgba(15, 112, 169, 0.5) !important;
        border-radius: 50px;
        box-shadow: 0 0 0 0;
        padding: 0;
        border: 1px solid #0F70A9;
        width: 118px;
      }

      .el-input__inner {
        padding-left: 15px;
        line-height: 32px;
        font-size: 16px;
        color: #02D9FD;
      }

      .el-input__suffix {
        padding-right: 15px;
      }

      .el-select .el-input__wrapper.is-focus {
        box-shadow: 0 0 0 0 !important;
      }

      .el-select .el-input.is-focus .el-input__wrapper {
        box-shadow: 0 0 0 0 !important;
      }
    }

    /* 中间折线图 */
    .line_center {
      width: 100%;
      height: 460px;
    }

    /* 左1模块 */
    .left_box1 {
      height: 500px;
      width: 100%;
      margin-bottom: 10px;
      position: relative;
    }

    /* //左2模块 */
    .left_box2 {
      height: 447px;
      width: 100%;
      margin-bottom: 10px;
    }

    /* //左3模块 */
    .left_box3 {
      height: 310px;
      width: 100%;
    }

    /* //右1模块 */
    .right_box1 {
      height: 500px;
      width: 100%;
      margin-bottom: 10px;
    }

    /* 右2模块 */
    .right_box2 {
      height: 447px;
      width: 100%;
      margin-bottom: 10px;
    }

    /* 右3模块 */
    .right_box3 {
      height: 310px;
      width: 100%;
    }

    /* 左1模块-玫瑰饼图 */
    #Rose_diagram {
      height: 90%;
      width: 100%;
    }

    /* 左1模块-圆环图 */
    .left_box1_rose_right {
      height: 85%;
      width: 55%;
      position: absolute;
      right: 0;
      top: 0;
    }

    /* 左1模块-文字部分 */
    .rose_text {
      display: inline-block;
      margin-top: 4%;
      margin-left: 4%;
    }

    /* 左1模块-￥符号样式 */
    .coin {
      font-size: 20px;
      color: #ffc107;
    }

    /* 左1模块-（件）样式 */
    .colorYellow {
      color: yellowgreen;
    }

    /* 左1模块-数字样式 */
    .rose_text_nmb {
      font-size: 20px;
      color: #00b891;
    }

    /* 左2模块 柱状图 */
    #columnar {
      height: 97%;
      width: 95%;
      margin-left: 3%;
      margin-top: 5px;
    }

    /* 折线图 */
    #line_center_diagram {
      height: 100%;
      width: 100%;
    }

    /* 轮播表格 */
    .carousel_list {
      width: 96%;
      height: 98%;
      margin-left: 10px;
    }

    /* 虚线柱状图*/
    #dotter_bar {
      width: 100%;
      height: 100%;
    }

    /* 锥形图 */
    .cone_box {
      width: 95%;
      height: 97%;
      margin-left: 3%;
    }
  }
</style>
</style>

</style>

